package com.tanhua.service;

import com.huanxin.HuanxinTemplate;
import com.tanhua.domain.User;
import com.tanhua.domain.UserInfo;
import com.tanhua.dubbo.UserAPI;
import com.tanhua.dubbo.UserInfoAPI;
import com.tanhua.dubbo.mongo.FriendAPI;
import com.tanhua.interceptor.UserHolder;
import com.tanhua.mongo.Friend;
import com.tanhua.vo.PageResult;
import com.tanhua.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MessageService {

    @DubboReference
    private UserAPI userAPI;

    @DubboReference
    private UserInfoAPI userInfoAPI;

    @Autowired
    private HuanxinTemplate huanxinTemplate;


    @DubboReference
    private FriendAPI friendAPI;

    public UserInfoVo findUserInfoByHuanxinId(String huanxinId) {
        User user = userAPI.findByHuanxinId(huanxinId);
        if (user!=null){
            UserInfo userInfo = userInfoAPI.findById(user.getId());

            UserInfoVo vo = new UserInfoVo();
            BeanUtils.copyProperties(userInfo,vo);
            if (userInfo.getAge()!=null){
                vo.setAge(userInfo.getAge().toString());
            }
            return vo;
        }
        return null;
    }

    public void createFriends(Long friendId) {
        //1 将用户的好友关系保存到环信
        Long userId = UserHolder.getUserId();
        huanxinTemplate.addFriend("hx"+userId,"hx"+friendId);

        //2 保存到mongoDB的firend表中
        friendAPI.save(userId,friendId);
    }

    public PageResult friendList(Integer page, Integer pagesize, String keyword) {
        //1 调用friendAPI用户的所有的好友信息
        List<Friend> firendList = friendAPI.findFirendList(UserHolder.getUserId());
        //2 去mysql中分页+条件查找符合的用户信息
        List<Long> firendIdList = firendList.stream().map(f -> f.getFriendId()).collect(Collectors.toList());
        //调用userInfoAPI，查找信息
        PageResult pr = userInfoAPI.findByCondition(page,pagesize,keyword,firendIdList);
        //3 封装？
        return pr;
    }
}
